package com.chu.cloud.zuul.filter.fallback;

import com.chu.cloud.enums.ResultEnums;
import com.chu.cloud.response.ResultVo;
import com.chu.cloud.util.JsonUtils;
import org.springframework.cloud.netflix.zuul.filters.route.ZuulFallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * @author: Tianshu.CHU
 * @Date: 2018/9/13 14:01
 */
@Component
public class AccessPermitFallback implements ZuulFallbackProvider {

    private final static ResultVo FALLBACK = new ResultVo(ResultEnums.OPEN_SERVER_FAIL);
    private final static byte[] RESPONSE = JsonUtils.obj2json(FALLBACK).getBytes();

    @Override
    public String getRoute() {
        return "open-microservice";
    }

    @Override
    public ClientHttpResponse fallbackResponse() {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.BAD_GATEWAY;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return getStatusCode().value();
            }

            @Override
            public String getStatusText() throws IOException {
                return getStatusCode().getReasonPhrase();
            }

            @Override
            public void close() {
            }

            @Override
            public InputStream getBody() throws IOException {
                return new ByteArrayInputStream(RESPONSE);
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                MediaType mediaType = new MediaType("application", "json", Charset.forName("UTF-8"));
                headers.setContentType(mediaType);
                return headers;
            }
        };
    }
}
